﻿using CodePlex.SharePoint.Explorer.Modules.Lists.ViewModels;
using James.SharePoint;
using JScriptSuite.Html;
using JScriptSuite.Html5;
using JScriptSuite.Html5.IO;
using JScriptSuite.JScriptLib.UI.Components;
using JScriptSuite.JScriptLib.UI.Controls.Lazy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodePlex.SharePoint.Explorer.Modules.Nodes
{
    class Uploader
    {
        readonly static HtmlLazy<Uploader> instance = new HtmlLazy<Uploader>(delegate () { return new Uploader(); });

        readonly HtmlInputFileElement input;
        Folder folder;

        Uploader()
        {
            if (SupportedHtml5Features.File)
            {
                input = (HtmlInputFileElement)ElementParking.CreateElements("<input type='file' multiply='1'/>")[0];
                input.AdviseChange(Change);
            }
        }

        void Change()
        {
            Upload(folder, input.Files);
        }

        internal static void Upload(Folder folder)
        {
            if (instance.Value.input != null)
            {
                instance.Value.folder = folder;
                instance.Value.input.Click();
            }
        }

        internal static async void Upload(Folder folder, HtmlCollection<File> files)
        {
            if(files.Length == 1)
            {
                File file = files[0];
                LazyWindow.ShowWaiting(string.Format("{0}: uploading...", file.Name));
                try
                {
                    ListItem listItem = await folder.Upload(file);
                    LazyWindow.HideWaiting();
                    ListItemEditor.Show(new EditAction() { EditMode = EditMode.Edit, ListItem = listItem, TargetList = listItem.ParentList });
                }
                catch (Exception e)
                {
                    LazyWindow.ShowError(e);
                }
            }
            else
            {
                Upload(folder, files, 0);
            }
        }

        static void Upload(Folder folder, HtmlCollection<File> files, int index)
        {
            if (index < files.Length)
            {
                File file = files[index];
                LazyWindow.ShowWaiting(string.Format("{0}: uploading...", file.Name));
                folder.Upload(file,
                    delegate (ListItem listItem)
                    {
                        LazyWindow.HideWaiting();
                        Upload(folder, files, index + 1);
                    },
                    LazyWindow.ShowError);

            }
        }
    }
}